package com.ysd.twocrm.shiro;

import com.ysd.twocrm.entity.Permission;
import com.ysd.twocrm.entity.Roles;
import com.ysd.twocrm.entity.Users;
import com.ysd.twocrm.mapper.PermissionMapper;
import com.ysd.twocrm.mapper.RolesMapper;
import com.ysd.twocrm.mapper.UsersMapper;
import com.ysd.twocrm.utils.MD5Utils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {
@Autowired
    private UsersMapper usersMapper;
@Autowired
private RolesMapper rolesMapper;
@Autowired
private PermissionMapper permissionMapper;

    //执行授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
         System.out.println("授权");
         //获得操作的主体
         Users u=(Users)principalCollection.getPrimaryPrincipal();
         //告诉shiro自己都有什么权限
        SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
        //先查询当前用户拥有的角色
        List<Roles> allRolesNameById = rolesMapper.getAllRolesNameById(u.getUserId());
        for(int i=0;i<allRolesNameById.size();i++){
            simpleAuthorizationInfo.addRole(allRolesNameById.get(i).getRoleName());//将当前角色名称加入进去
          //  System.out.println("角色名称："+allRolesNameById.get(i).getRoleName());
        }
        //查询当前用户所拥有的权限
        List<Permission> permissionList = permissionMapper.PERMISSION_LIST(u.getUserId());
        for(int i=0;i<permissionList.size();i++){
            simpleAuthorizationInfo.addStringPermission(permissionList.get(i).getPermissionValue());
         //   System.out.println("角色权限值："+permissionList.get(i).getPermissionValue());
        }
        return simpleAuthorizationInfo;
    }
    //执行认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
      System.out.println("开始认证");
        String userLoginName=(String) authenticationToken.getPrincipal();//获得登录名
        Users user = usersMapper.findUserLoginName(userLoginName);//根据登录名查询当前用户
        if(user==null){
            System.out.println("认证失败");//认证失败
            return null;
        }else{
System.out.println("认证成功");
//认证成功时，来去判断密码，用shiro内置的方法，传入三个值，第一个是用户角色、第二个是密码、第三个是当前的realm对象
            SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(user,user.getUserPassword(),user.getUserName());
            return simpleAuthenticationInfo;

        }

    }
}
